package Tree;

/**
 * @BelongsProject: SeniorArchitect-LeetCode
 * @BelongsPackage: Tree
 * @Author: zhuangxiaoyan
 * @CreateTime: 2023-10-30  08:58
 * @Description: TODO
 * @Version: 1.0
 */
public class 平衡二叉树110 {

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        return getHeight(root) == -1 ? false : true;
    }

    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getHeight(root.left);
        if (leftH == -1) {
            return -1;
        }
        int rightH = getHeight(root.right);
        if (rightH == -1) {
            return -1;
        }
        return Math.abs(leftH - rightH) > 1 ? -1 : 1 + Math.max(leftH, rightH);
    }

    public boolean isbalance(TreeNode root) {
        if (root == null) {
            return true;
        }
        return getH(root) == -1 ? false : true;
    }

    private int getH(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftH = getH(root.left);
        if (leftH == 1) {
            return -1;
        }
        int rightH = getH(root.right);
        if (rightH == -1) {
            return -1;
        }
        return Math.abs(leftH - rightH) > 1 ? -1 : Math.min(leftH, rightH);
    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
